package cn.itcast.bos.web.action.system;


import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.UserService;
import cn.itcast.bos.web.action.common.BaseAction;

@SuppressWarnings("serial")
@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User>{
	
	@Autowired
	private UserService userService;
	private Logger logger = Logger.getLogger(User.class);
	
	/**
	 * 用户登录，身份验证
	 * @return
	 */
	@Action(value="user_login",results={
			@Result(name="success",type="redirect",location="index.html"),
			@Result(name="input", type="redirect",location="login.html")})
	public String userLogin(){
		//基于shiro登录
		Subject subject = SecurityUtils.getSubject();
		//用户验证
		AuthenticationToken token = new UsernamePasswordToken(model.getUsername(),model.getPassword());
		logger.info(model.getUsername()+":"+model.getPassword());
		try {
			//登录成功
			subject.login(token);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
	}
	
	
	/**
	 * 注销登录
	 */
	@Action(value="user_logout",results={@Result(name="success",location="login.html",type="redirect")})
	public String user_logout(){
		try {
			Subject subject = SecurityUtils.getSubject();
			subject.logout();
			return SUCCESS;
		} catch (Exception e) {
			logger.info(e.getMessage());
			throw new RuntimeException();
		}
	}
	
	@Action(value="user_list",results={@Result(name="success",type="json")})
	public String findUser(){
		List<User> users = userService.findAll();
		ActionContext.getContext().getValueStack().push(users);
		return SUCCESS;
	}
	
	//获取封装的roleId
	private String[] roleIds;
	
	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}


	@Action(value="user_save",results={@Result(name="success",type="redirect",location="pages/system/userlist.html")})
	public String saveUser(){
		userService.save(model,roleIds);
		return SUCCESS;
	}
}
